<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="部门名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="部门状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:dept:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      border
      v-loading="loading"
      :data="deptList"
      row-key="deptId"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="deptName" label="部门名称" width="260"></el-table-column>
      <el-table-column prop="orderNum" label="排序" width="200"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dept:edit']"
            >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:dept:add']"
            >新增
          </el-button>
          <el-button
            v-if="scope.row.parentId != 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dept:remove']"
            >删除
          </el-button>
          <el-button
            v-if="scope.row.deptType == '7'"
            size="mini"
            type="text"
            icon="el-icon-upload2"
            @click="handleImport(scope.row)"
            >导入
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-setting" @click="handleSystem(scope.row.deptId)"
            >应用库配置
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-setting" @click="handleConfig(scope.row.deptId)"
            >卡片配置
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-setting" @click="handleVisualization(scope.row.deptId)"
            >大屏卡片配置
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <help-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <treeselect
                v-model="form.parentId"
                :options="deptOptions"
                :normalizer="normalizer"
                placeholder="选择上级部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所在区域" prop="areaCode">
              <el-cascader
                :options="regionData"
                v-model="form.areaCode"
                style="width: 100%"
                :props="{ checkStrictly: true }"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="组织类型" prop="deptType">
              <el-select v-model="form.deptType" placeholder="请选择组织类型">
                <el-option
                  v-for="dict in dict.type.sys_dept_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
            <el-form-item label="平台主名称">
              <el-input v-model="form.platformName" placeholder="请输入平台主名称" />
            </el-form-item>
            <el-form-item label="平台logo">
              <y-upload :path="[form.logoPath]" accept=".ico" limit="1" @onSuccess="onSuccess" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value"
                  >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="平台副名称">
              <el-input v-model="form.platformPrimaryName" placeholder="请输入平台副名称" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </help-dialog>

    <help-dialog title="组织导入" :visible.sync="uploadDialogVisible" width="30%" align="center" @close="closeUpload">
      <el-upload class="upload-demo" drag action="#" :http-request="imported" multiple ref="upload" accept=".xlsx,.xls">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传xlsx、xls文件，且不超过500kb</div>
      </el-upload>
      <el-button type="text" @click="templateDownload">组织导入模版</el-button>
    </help-dialog>

    <help-dialog title="应用库配置" :visible.sync="dialogVisible" width="70%">
      <el-table :data="appMenuList" ref="table" border tooltip-effect="dark" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="图标" align="center">
          <template slot-scope="scope">
            <y-show-all-file :path="scope.row.icon" height="50px" width="50px" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="菜单名称" align="center" />
        <el-table-column align="center" label="功能简介" prop="moduleIntroduction" show-overflow-tooltip />
        <el-table-column align="center" label="相对路由" prop="component" show-overflow-tooltip />
        <el-table-column align="center" label="跳转类型" prop="">
          <template slot-scope="scope">
            {{ scope.row.skipType == 1 ? '系统外页面' : '系统内页面' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否收费">
          <template slot-scope="scope">
            {{ scope.row.isCharge == 1 ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="模块价格" prop="price" />
        <el-table-column align="center" label="是否宣展">
          <template slot-scope="scope">
            {{ scope.row.flag == 1 ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="面向用户">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_user_oriented" :value="scope.row.directionUser" />
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleUpdateApp">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </help-dialog>
    <help-dialog title="卡片配置" :visible.sync="cardVisible">
      <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddCard" style="margin-bottom: 20px"
        >新增
      </el-button>
      <el-table :data="cardList" border size="small" v-loading="loading">
        <el-table-column align="center" label="角色" prop="roleName" />
        <el-table-column align="center" label="角色id" prop="roleId" />
        <el-table-column align="center" label="创建时间" prop="createDate" />
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="handleEditCard(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="cardTotal > 0"
        :total="cardTotal"
        :page.sync="query.pageNum"
        :limit.sync="query.pageSize"
        @pagination="getConfigList"
      />
    </help-dialog>

    <help-dialog title="卡片配置" :visible.sync="addVisible" append-to-body>
      <el-table
        v-show="active == 0"
        :data="configList"
        ref="addTable"
        border
        tooltip-effect="dark"
        @selection-change="handleChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column align="center" label="卡片名称" prop="name" />
        <el-table-column align="center" label="组件名称" prop="componentName" />
        <el-table-column align="center" label="卡片尺寸" prop="sizeLabel" />
        <el-table-column align="center" label="面向用户" prop="platformLabel" />
        <el-table-column align="center" label="应用归宿" prop="chargeTypeLabel" />
        <el-table-column align="center" label="添加时间" prop="createDate" />
      </el-table>
      <div v-show="active == 1 && !id">
        <el-table
          :data="roleList"
          ref="roleTable"
          tooltip-effect="dark"
          row-key="roleId"
          :tree-props="{ children: 'children' }"
          @selection-change="handleChangeRole"
          border
        >
          <el-table-column type="selection" width="55" align="center" :selectable="selectable" />
          <el-table-column label="角色编号" align="center" prop="roleId" />
          <el-table-column label="角色名称" align="center" prop="roleName" />
          <el-table-column label="权限字符" align="center" prop="roleKey" />
          <el-table-column label="创建时间" align="center" prop="createTime">
            <template slot-scope="scope">
              <span>{{ scope.row.createTime }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="roleTotal > 0"
          :total="roleTotal"
          :page.sync="params.pageNum"
          :limit.sync="params.pageSize"
          @pagination="getRoleList"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="active == 0 && !id" type="primary" @click="active = '1'">下一步</el-button>
        <el-button v-show="active == 1 && !id" type="warning" plain @click="active = '0'">上一步</el-button>
        <el-button v-show="active == 1 && !id" type="primary" @click="handleCard">确 定</el-button>
        <el-button v-show="active == 0 && id" type="primary" @click="handleCardUpdate">确 定</el-button>
        <el-button @click="addVisible = false">取 消</el-button>
      </div>
    </help-dialog>

    <help-dialog title="大屏应用模块配置" :visible.sync="dialogVisualization">
      <el-table
        :data="visualizationList"
        border
        size="small"
        ref="visualizationTable"
        @selection-change="changeVisualization"
      >
        <el-table-column type="selection" align="center" width="55" />
        <el-table-column fixed type="index" align="center" width="50" label="序号" />
        <el-table-column align="center" label="卡片名称" prop="cardName" />
        <el-table-column align="center" label="组件名称" prop="cardComponentName" />
        <el-table-column align="center" label="卡片尺寸" prop="cardSizeLabel" />
        <el-table-column align="center" label="添加时间" prop="createDate" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateVisualization">确 定</el-button>
        <el-button @click="dialogVisualization = false">取 消</el-button>
      </div>
    </help-dialog>
  </div>
</template>

<script>
import {
  addDept,
  delDept,
  getDept,
  importDept,
  listDept,
  listDeptExcludeChild,
  updateDept,
  deptAppMenu,
  deptAppMenuSave,
  cardConfig,
  userConfigList,
  configuredRoleId,
  cardConfigSave,
  cardConfigUpdate,
  deptVisualizationCardList,
  deptVisualizationUpdate
} from '@/api/system/dept'
import { listRole } from '@/api/system/role'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { regionData } from 'element-china-area-data'
import { download } from '@/utils/fileUtils'
import th from 'element-ui/src/locale/lang/th'

export default {
  name: 'Dept',
  dicts: ['sys_normal_disable', 'sys_dept_type'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        areaCode: [{ required: true, message: '所在区域不能为空', trigger: 'blur' }],
        parentId: [{ required: true, message: '上级部门不能为空', trigger: 'blur' }],
        deptName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
        orderNum: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
        deptType: [{ required: true, message: '组织类型不能为空', trigger: 'blur' }],
        email: [
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ]
      },
      regionData,
      uploadDialogVisible: false,
      dialogVisible: false,
      // 应用库配置
      appMenuList: [],
      selectList: [],
      cardVisible: false,
      cardList: [],
      cardTotal: 0,
      query: {
        deptId: '',
        pageNum: 1,
        pageSize: 10
      },
      configList: [],
      // 添加卡片配置
      addVisible: false,
      // 添加 选择的卡片id列表
      cardIdList: [],
      active: '0',
      // 角色列表查询参数
      params: {
        pageNum: 1,
        pageSize: 10
      },
      roleList: [],
      roleTotal: 0,
      // 添加卡片配置 选择的角色id
      roleIdList: [],
      selectableRole: [],
      id: '',
      dialogVisualization: false,
      visualizationList: [],
      selectVisualization: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true
      listDept(this.queryParams).then((response) => {
        this.deptList = this.handleTree(response.data, 'deptId')
        this.loading = false
      })
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: '0'
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    onSuccess(url) {
      this.form.logoPath = url.router
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      if (row != undefined) {
        this.form.parentId = row.deptId
      }
      this.open = true
      this.title = '添加部门'
      listDept().then((response) => {
        this.deptOptions = this.handleTree(response.data, 'deptId')
      })
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      getDept(row.deptId).then((response) => {
        this.form = response.data
        this.form.areaCode = this.form.areaCode.split(',')
        this.open = true
        this.title = '修改部门'
        listDeptExcludeChild(row.deptId).then((response) => {
          this.deptOptions = this.handleTree(response.data, 'deptId')
          if (this.deptOptions.length == 0) {
            const noResultsOptions = { deptId: this.form.parentId, deptName: this.form.parentName, children: [] }
            this.deptOptions.push(noResultsOptions)
          }
        })
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.areaCode = this.form.areaCode.join(',')
          if (this.form.deptId != undefined) {
            updateDept(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addDept(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除名称为"' + row.deptName + '"的数据项？')
        .then(function () {
          return delDept(row.deptId)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    handleImport(row) {
      this.deptId = row.deptId
      this.parentId = row.parentId
      this.uploadDialogVisible = true
    },
    imported(item) {
      var formData = new FormData()
      formData.append('file', item.file)
      importDept(formData, `${this.parentId},${this.deptId}`).then((res) => {
        this.$message.success('导入成功')
        this.closeUpload()
        this.getList()
      })
    },
    templateDownload() {
      download('/profile/upload/2023/5/29/temp_fd718c23febf4561b9c9e2b1ebbece7c.xls')
    },
    closeUpload() {
      this.$refs.upload.clearFiles()
      this.uploadDialogVisible = false
    },
    handleSystem(deptId) {
      this.deptId = deptId
      deptAppMenu({ deptId: deptId }).then((res) => {
        this.appMenuList = res.data.systemAppMenuList
        this.dialogVisible = true
        res.data.deptAppMenuList.map((e) => {
          res.data.systemAppMenuList.map((v) => {
            if (e == v.id) {
              this.$nextTick(() => {
                this.$refs.table.toggleRowSelection(v)
              })
            }
          })
        })
      })
    },
    handleSelectionChange(item) {
      this.selectList = item.map((e) => e.id)
    },
    handleUpdateApp() {
      deptAppMenuSave({ deptId: this.deptId, appIdList: this.selectList }).then((res) => {
        this.$message.success('操作成功')
        this.dialogVisible = false
      })
    },
    handleConfig(deptId) {
      this.deptId = deptId
      this.getConfigList()
      this.cardVisible = true
    },
    getConfigList() {
      cardConfig({ ...this.query, deptId: this.deptId }).then((res) => {
        this.cardList = res.data.records
        this.cardTotal = res.data.total
      })
    },
    handleAddCard() {
      this.getRoleList()
      userConfigList().then((res) => {
        this.configList = res.data
        this.addVisible = true
      })
    },
    handleChange(select) {
      this.cardIdList = select.map((e) => e.id)
    },
    async getRoleList() {
      const { rows, total } = await listRole(this.params)
      this.roleList = rows
      this.roleTotal = total
      const { data } = await configuredRoleId({ deptId: this.deptId })
      this.selectableRole = data
    },
    handleChangeRole(select) {
      this.roleIdList = select.map((e) => e.roleId)
    },
    selectable(row) {
      return !this.selectableRole.includes(row.roleId)
    },
    handleCard() {
      if (this.roleIdList.length > 0) {
        cardConfigSave({ deptId: this.deptId, roleIdList: this.roleIdList, cardIdList: this.cardIdList }).then(
          (res) => {
            this.$message.success('添加成功')
            this.addVisible = false
            this.active = '0'
            this.id = ''
            this.getConfigList()
          }
        )
      }
    },
    handleEditCard(row) {
      this.id = row.id
      userConfigList().then((res) => {
        this.configList = res.data
        this.addVisible = true
        this.$nextTick(() => {
          row.cardIdList.map((e) => {
            this.configList.map((v) => {
              if (e == v.id) {
                this.$refs.addTable.toggleRowSelection(v)
              }
            })
          })
        })
      })
    },
    handleCardUpdate() {
      cardConfigUpdate({ id: this.id, cardIdList: this.cardIdList, isDelete: '' }).then((res) => {
        this.$message.success('修改成功')
        this.addVisible = false
        this.active = '0'
        this.id = ''
        this.getConfigList()
      })
    },
    // 大屏配置
    handleVisualization(deptId) {
      this.deptId = deptId
      deptVisualizationCardList({ deptId: deptId }).then((res) => {
        this.visualizationList = res.data.selectList

        res.data.checkedList.map((e) => {
          this.visualizationList.map((v) => {
            if (e.id === v.id) {
              this.$nextTick(() => {
                this.$refs.visualizationTable.toggleRowSelection(v)
              })
            }
          })
        })
        this.dialogVisualization = true
      })
    },
    changeVisualization(val) {
      this.selectVisualization = val.map((e) => {
        return e.id
      })
    },
    updateVisualization() {
      deptVisualizationUpdate({ cardIdList: this.selectVisualization, deptId: this.deptId }).then((res) => {
        this.$message.success('配置成功')
        this.dialogVisualization = false
      })
    }
  }
}
</script>